<template>
  <el-dialog
    v-model="controlIsShowDialog"
    width="500px"
    :title="modelId ? '修改权限' : '新建权限'"
    draggable
    align-center
    destroy-on-close
    :before-close="handleCloseDialog"
    :show-close="!refForm?.stateIsSavingData"
    :close-on-click-modal="!refForm?.stateIsSavingData"
    :close-on-press-escape="!refForm?.stateIsSavingData"
  >
    <div class="content" :style="{ height: props.height ? props.height : '' }">
      <comp-add-or-edit-permis-manage
        ref="refForm"
        :id="modelId"
        @save-data-success="
          () => {
            controlIsShowDialog = false
            emits('saveDataSuccess')
          }
        "
      />
    </div>
    <template #footer>
      <el-button
        v-if="!modelId"
        type="primary"
        :icon="Select"
        :loading="refForm?.stateIsSavingData"
        @click="refForm?.handleAddOrEditData"
      >
        保存
      </el-button>
      <el-button
        v-else
        type="success"
        :icon="Edit"
        :loading="refForm?.stateIsSavingData"
        @click="refForm?.handleAddOrEditData"
      >
        保存更改
      </el-button>
      <el-button
        :icon="Refresh"
        :loading="refForm?.stateIsSavingData"
        @click="refForm?.handleResetData"
        title="恢复到默认值"
      >
        重置
      </el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { Edit, Refresh, Select } from '@element-plus/icons-vue'
  import { ref } from 'vue'
  import CompAddOrEditPermisManage from '/@/views/manage/permission/addAndEdit/CompAddOrEditPermisManage.vue'

  // ref变量
  const refForm = ref<any>()

  const modelId = ref<number>() // 回显对象id

  // 控制变量
  const controlIsShowDialog = ref<boolean>(false) // 是否显示对话框

  const emits = defineEmits<{ (e: 'saveDataSuccess'): void }>()

  const props = withDefaults(
    defineProps<{
      height: string // 固定对话框高度（超出部分会滚动），如果传入空则自适应内部元素高度，默认自适应高度
    }>(),
    { height: '' }
  )

  /**
   * 打开对话框
   * @param id 详情对话框操作的对象的id
   */
  const handleOpenDialog = (id?: number) => {
    modelId.value = id
    controlIsShowDialog.value = true
  }

  /**
   * 关闭对话框的操作，调用done()后才会关闭对话框
   * @param done 关闭回调
   */
  const handleCloseDialog = async (done: () => void) => {
    // 如果正在修改数据，则不允许关闭对话框
    if (refForm.value.stateIsSavingData) {
      return
    }
    // 是否可以安全关闭对话框
    if (!(await refForm.value.handleCheckSafetyClose())) {
      return
    }
    done()
  }

  // 导出的对象，可以让上级组件访问到。必须放到导出的对象下面，否则导致对象未声明
  defineExpose({ handleOpenDialog, controlIsShowDialog })
</script>
<style lang="scss" scoped>
  .content {
    overflow-y: auto;
    overflow-x: hidden;
  }
</style>